use talktive::HistoryEncoder;

use crate::role::Role;

#[derive(Debug, Clone)]
pub struct Encoder {}

impl Encoder {
    fn encode(s: &mut String, msg: &talktive::Message<Role>) {
        s.push_str(&format!("<|{}|>\n{}\n", msg.role_name(), msg.content()));
    }
}
impl HistoryEncoder for Encoder {
    type BatchEncodedType = String;

    type MessageRole = Role;

    fn history_prefix_encode_batch(
        batch: &Self::BatchEncodedType,
        messages: &Vec<talktive::Message<Self::MessageRole>>,
    ) -> Self::BatchEncodedType {
        let mut res = String::new();
        for msg in messages {
            Self::encode(&mut res, msg);
        }
        let res = batch.clone() + &res;
        res
    }

    fn history_push_encode_batch(
        batch: &mut Self::BatchEncodedType,
        messages: &Vec<talktive::Message<Self::MessageRole>>,
    ) -> anyhow::Result<()> {
        for msg in messages {
            Self::encode(batch, msg);
        }
        Ok(())
    }

    fn history_push_encode_single(
        batch: &mut Self::BatchEncodedType,
        message: talktive::Message<Self::MessageRole>,
    ) -> anyhow::Result<()> {
        Self::encode(batch, &message);
        Ok(())
    }
}
